package com.estronger.shopmanage.ui.order.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.ui.order.adapter.ShowImagesAdapter;
import com.estronger.shopmanage.ui.order.adapter.TaoCan_Detail_ItemAdapter;
import com.estronger.shopmanage.ui.order.bean.OrderAttributeBean;
import com.estronger.shopmanage.ui.order.bean.OrderBean;
import com.estronger.shopmanage.ui.order.bean.returnMsgEntity;
import com.estronger.shopmanage.ui.order.until.Tools;
import com.estronger.shopmanage.utils.NetUtils;
import com.estronger.shopmanage.utils.ScreenUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.CircularProgress;
import com.estronger.shopmanage.view.CustomGlridView;
import com.estronger.shopmanage.view.CustomListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.soonfor.evaluate.activity.ShowPicActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.jesse.nativelogger.NLogger;

/**
 * Created by DingYG on 2017-08-09.
 */

public class OrderDetailActivity extends BaseActivity {

    private OrderBean orderTou = null;
    private Activity mActivity;
    private View rootView;//根目录View
    private ScrollView sv_root;
    private TextView tvfTitle, tvfHouseAndName, tvfPhone, tvfAddress, tvfOrderTime;
    private TextView tvfAction, tvfMealType, tvfSerizes, tvfStyle, tvfTexture, tvfColor,
            tvfYjazTime, tvfSkType, tvfSkMoney, tvfRemark;
    private CustomGlridView gvfShowPics;
    private LinearLayout llfOtherAttribute, llFour;
    private CustomListView lvfOther;
    private ImageView ivfBottom;
    private ShowImagesAdapter showAdapter;
    private List<OrderAttributeBean> codList;
    private ArrayList<String> imgPaths;
    private String reMark = "";
    protected CircularProgress bar;// 进度条

    @Override
    protected void init() {
        super.init();
        Tools.LastPost = getIntent().getIntExtra("LASTPOST", 0);
        orderTou = (OrderBean) getIntent().getSerializableExtra("Order");
        codList = new ArrayList<>();
        imgPaths = new ArrayList<>();
    }

    @Override
    protected void initView() {
        super.initView();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mActivity = OrderDetailActivity.this;
        rootView = View.inflate(mActivity, R.layout.layout_activity_orderquery_detail, null);
        setContentView(rootView);
        tvfTitle = (TextView) findViewById(R.id.ab_title);
        tvfHouseAndName = (TextView) findViewById(R.id.tvfQTitle);
        tvfPhone = (TextView) findViewById(R.id.tvfQPhoneno);
        tvfAddress = (TextView) findViewById(R.id.tvfQItemLocation);
        tvfOrderTime = (TextView) findViewById(R.id.tvfQOrderTime);
        tvfTitle.setText("预订单详情");
        String housAndName = "";
        if (orderTou.getfHouses().equals("")) {
            housAndName = orderTou.getfCusName();
        } else {
            housAndName = orderTou.getfHouses() + "-" + orderTou.getfCusName();
        }
        tvfHouseAndName.setText(housAndName);
        tvfPhone.setText(orderTou.getfPhoneNumber());
        tvfOrderTime.setText(orderTou.getfOrdersTime());
        sv_root = (ScrollView) findViewById(R.id.slfDetail);
        findViewAndSetEvent(sv_root);
    }

    private void findViewAndSetEvent(View root) {
        ivfBottom = (ImageView) findViewById(R.id.ivfBottom);
        tvfAction = (TextView) root.findViewById(R.id.tvfQAction);
        tvfMealType = (TextView) root.findViewById(R.id.tvfQMealType);
        tvfSerizes = (TextView) root.findViewById(R.id.tvfQSeries);
        tvfStyle = (TextView) root.findViewById(R.id.tvfQStyles);
        tvfTexture = (TextView) root.findViewById(R.id.tvfQTexture);
        tvfColor = (TextView) root.findViewById(R.id.tvfQColor);

        tvfYjazTime = (TextView) root.findViewById(R.id.tvfQyjazDate);
        tvfSkType = (TextView) root.findViewById(R.id.tvfQSkType);
        tvfSkMoney = (TextView) root.findViewById(R.id.tvfQSkMoney);

        llFour = (LinearLayout) root.findViewById(R.id.llFour);
        tvfRemark = (TextView) root.findViewById(R.id.tvfQRemark);
        gvfShowPics = (CustomGlridView) root.findViewById(R.id.gvfCpImages);
        llfOtherAttribute = (LinearLayout) root.findViewById(R.id.llfQOtherAttribute);
        lvfOther = (CustomListView) root.findViewById(R.id.clvQOther);
        bar = (CircularProgress) rootView.findViewById(R.id.loding_view);
        if (ScreenUtils.getNavigationBarHeight(mActivity) > 0) {
            ivfBottom.setVisibility(View.VISIBLE);
        } else {
            ivfBottom.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initAction() {
        super.initAction();
        loadData();
    }
    /**
     * 加载数据
     */
    private void showData() {
        MyHandler myHandle = new MyHandler();
        Message msg = new Message();
        myHandle.handleMessage(msg);
    }
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                if (codList.size() > 0) {
                    llfOtherAttribute.setVisibility(View.VISIBLE);
                    TaoCan_Detail_ItemAdapter taAdapter = new TaoCan_Detail_ItemAdapter(mActivity, codList);
                    lvfOther.setAdapter(taAdapter);
                } else {
                    llfOtherAttribute.setVisibility(View.GONE);
                }
                if (imgPaths.size() == 0 && reMark.equals("")) {
                    llFour.setVisibility(View.GONE);
                } else {
                    llFour.setVisibility(View.VISIBLE);
                    if (imgPaths.size() > 0) {
                        gvfShowPics.setVisibility(View.VISIBLE);
                        showAdapter = new ShowImagesAdapter(mActivity, imgPaths);
                        gvfShowPics.setAdapter(showAdapter);
                        if (showAdapter.getCount() > 12) {
                            Tools.setListViewHeightBasedOnChildren(gvfShowPics, 4, 3);
                            dimssDialog2();
                        }
                        gvfShowPics.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Bundle bundle1 = new Bundle();
                                bundle1.putStringArrayList("piclists", imgPaths);
                                bundle1.putInt("position", position);
                                Intent intent = new Intent(mActivity, ShowPicActivity.class);
                                intent.putExtras(bundle1);
                                mActivity.startActivity(intent);
                            }
                        });
                    } else {
                        gvfShowPics.setVisibility(View.GONE);
                    }
                }
            } catch (Exception e) {
                NLogger.e("崩溃异常收集:" + e.getMessage());
            }
        }
    }

    public void loadData() {
        try {
            if (!NetUtils.isNetworkConnected(mActivity)) {
                Toast.show(mActivity, "当前无网络链接！", 2000);
                return;
            }
            String url = MyApplication.getApplication().getSERVER_URL() + "/web/common/API/apphandler.ashx";
            RequestParams params = new RequestParams();
            params.addBodyParameter("sf_action", "getpreordinfo");
            params.addBodyParameter("usercode", MyApplication.getUserCode());
            params.addBodyParameter("ordid", orderTou.getfItemId());

            HttpUtils httpUtils = new HttpUtils();
            httpUtils.configTimeout(15 * 1000).configSoTimeout(15 * 1000).configRequestRetryCount(3);
            httpUtils.configCurrentHttpCacheExpiry(0);
            httpUtils.send(HttpRequest.HttpMethod.POST, url, params,
                    new RequestCallBack<String>() {
                        @Override
                        public void onStart() {
                            super.onStart();
                            if (null != bar) bar.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            try {
                                returnMsgEntity re = Tools.jsonResolve_returnMsgEntity(responseInfo.result);
                                if (re != null) {
                                    if (re.getSuccess()) {
                                        JSONObject jj = new JSONObject(re.getDataJson());
                                        String orddata = jj.getString("orddata");
                                        JSONObject jo = new JSONObject(orddata);
                                        if (jo != null) {
                                            tvfAddress.setText(Tools.ToString(jo.getString("deliveradd")));
                                            tvfAction.setText(Tools.ToString(jo.getString("activitytitle")));
                                            tvfMealType.setText(Tools.ToString(jo.getString("activitysuitename")));
                                            tvfSerizes.setText(Tools.ToString(jo.getString("kitname")));
                                            tvfStyle.setText(Tools.ToString(jo.getString("stylename")));
                                            tvfTexture.setText(Tools.ToString(jo.getString("rmqltname")));
                                            tvfColor.setText(Tools.ToString(jo.getString("clrname")));
                                            tvfSkType.setText(Tools.ToString(jo.getString("receivetypedesc")));
                                            tvfSkMoney.setText(Tools.ToString(jo.getString("receiveamt")));
                                            reMark = Tools.ToString(jo.getString("remark"));
                                            tvfRemark.setText(reMark);
                                            String orddate = Tools.ToString(jo.getString("orddate"));
                                            if (!orddate.equals("") && orddata.contains(" ")) {
                                                tvfYjazTime.setText(Tools.getDateFromFormatter(orddate));
                                            }
                                        }
                                        String codedata = jj.getString("codedata");
                                        JSONArray jc = new JSONArray(codedata);
                                        if (jc != null && jc.length() > 0) {
                                            for (int i = 0; i < jc.length(); i++) {
                                                JSONObject joo = jc.getJSONObject(i);
                                                OrderAttributeBean codeBean = new OrderAttributeBean();
                                                codeBean.setAttId(Tools.ToString(joo.getString("propertycode")));
                                                codeBean.setAttName(Tools.ToString(joo.getString("propertyname")));
                                                codeBean.setAffiliatedid(Tools.ToString(joo.getString("code")));
                                                codeBean.setAffiliatedName(Tools.ToString(joo.getString("codename")));
                                                codList.add(codeBean);
                                            }
                                        }
                                        String imgdata = jj.getString("imgdata");
                                        JSONArray ji = new JSONArray(imgdata);
                                        if (ji != null && ji.length() > 0) {
                                            for (int j = 0; j < ji.length(); j++) {
                                                JSONObject jioo = ji.getJSONObject(j);
                                                //加载图片
                                                String purl = MyApplication.getApplication().getSERVER_URL()
                                                        + "/web/common/Handler/file_download.ashx?filepath=" + Tools.ToString(jioo.getString("path"));
                                                imgPaths.add(purl);
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                e.getMessage();
                            }
                            if (null != bar) bar.setVisibility(View.GONE);
                            showData();
                        }

                        @Override
                        public void onFailure(HttpException e, String s) {
                            if (null != bar) bar.setVisibility(View.GONE);
                            showData();
                        }
                    });
        } catch (Exception e) {
            NLogger.e("加载统计数据异常:" + e.getMessage());
        }
    }


}
